package com.example.zookeeper.rmi.client;

import com.example.zookeeper.rmi.service.HelloService;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

public class ZkRmiClient
{
    private ZooKeeper zooKeeper;

    private final String ZK_RMI_REGISTRY_PATH = "/rmi_registry";

    private volatile List<String> urlList = new ArrayList<>();

    public ZkRmiClient()
    {
        initZookeeper();
        watchNode();
    }

    private void watchNode()
    {
        try
        {
            List<String> nodes = zooKeeper.getChildren(ZK_RMI_REGISTRY_PATH, watchedEvent -> watchNode());
            if (!CollectionUtils.isEmpty(nodes))
            {
                urlList.clear();
                nodes.stream().filter(s -> !StringUtils.isEmpty(s)).forEach(node ->
                {
                    String path = ZK_RMI_REGISTRY_PATH + "/" + node;
                    System.out.println("get node path:" + path);
                    try
                    {
                        byte[] data = zooKeeper.getData(path, null, new Stat());
                        urlList.add(new String(data));
                    } catch (KeeperException | InterruptedException e)
                    {
                        e.printStackTrace();
                    }
                });
            }
        } catch (KeeperException | InterruptedException e)
        {
            e.printStackTrace();
        }
    }

    private String lookupUrl()
    {
        if (CollectionUtils.isEmpty(urlList))
        {
            return null;
        }

        int size = urlList.size();
        if (size == 1)
        {
            return urlList.get(0);
        }
        else
        {
            return urlList.get(ThreadLocalRandom.current().nextInt(size));
        }
    }

    private <T extends Remote> T lookupService(String url, Class<T> tClass)
    {
        try
        {
            Remote remote = Naming.lookup(url);
            return tClass.cast(remote);
        } catch (NotBoundException | MalformedURLException | RemoteException e)
        {
            e.printStackTrace();
        }
        return null;
    }

    private <T extends Remote> T lookup(Class<T> clazz)
    {
        String url = lookupUrl();
        if (url == null)
        {
            return null;
        }
        return lookupService(url, clazz);
    }

    private void initZookeeper()
    {
        if (zooKeeper == null)
        {
            synchronized (this)
            {
                if (zooKeeper == null)
                {
                    final CountDownLatch latch = new CountDownLatch(1);
                    ZooKeeper zooKeeper = null;
                    try
                    {
                        zooKeeper = new ZooKeeper("192.168.3.91:2181", 10 * 1000, watchedEvent ->
                        {
                            System.out.println("zookeeper 连接成功");
                            latch.countDown();
                        });
                    } catch (IOException e)
                    {
                        e.printStackTrace();
                    }
                    try
                    {
                        latch.await();
                    } catch (InterruptedException e)
                    {
                        e.printStackTrace();
                    }
                    this.zooKeeper = zooKeeper;
                }
            }
        }
    }

    public static void main(String[] args) throws RemoteException
    {
        ZkRmiClient zkRmiClient = new ZkRmiClient();


        while (true)
        {
            HelloService helloService = zkRmiClient.lookup(HelloService.class);
            if (helloService != null)
            {
                String s = helloService.sayHello("zkClient");
                System.out.println(s);
            }

            try
            {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e)
            {
                e.printStackTrace();
                break;
            }
        }

    }
}
